package com.codingapi.p2p.client.handler.peer;


import com.codingapi.p2p.client.utils.SocketUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.udt.nio.NioUdtProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * create by lorne on 2018/3/28
 */
public class ByteEchoPeerHandler extends ChannelInboundHandlerAdapter {

    private static final Logger log = LoggerFactory.getLogger(ByteEchoPeerHandler.class);

    @Override
    public void channelActive(final ChannelHandlerContext ctx) {
        log.info("ECHO active " +
                NioUdtProvider.socketUDT(ctx.channel()).toStringOptions());

        SocketUtils.send(ctx.channel(),"xxxxx".getBytes());
    }

    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) {
        ByteBuf in = (ByteBuf)msg;
        byte[] bytes = new byte[in.writerIndex()];
        in.readBytes(bytes);
        String message  = new String(bytes);
        log.info("===Server reciever message:" +message);
        String ackMessage = "hello client ...";

        SocketUtils.send(ctx.channel(),ackMessage.getBytes());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
